#coding=utf-8
import urllib2, urllib,socket, os, pickle, datetime, sys
modify_url = 'https://www.dnspod.com/API/Record.Modify'
jayproxy_domain_id = '340422'
www_record_id = '1376388'
jayproxy_url = 'http://www.jayproxy.com/jayproxy.pac'

vps = {'fdd':['A', '69.197.153.239'],
    #'rp':['CNAME', 'ghs.jayproxy.com'],
    'hp':['A', '218.75.54.186'],
    #'bt':['A', '173.212.207.16'],

    'zjuer':['A', '64.71.167.13'],
    }

def modify(record_type, value):
    data = {'login_email':'xiaojay@gmail.com',
            'login_password':'101783',
            'format':'json',
            'domain_id':jayproxy_domain_id,
            'record_id':www_record_id,
            'sub_domain':'www',
            'record_type':record_type,
            'record_line':'default',
            'value':value,
            'mx':'1',
            'ttl':'600'}
    f = urllib2.urlopen(modify_url, urllib.urlencode(data))
    if f.getcode() == 200:
        print 'modify %s -> %s'%(record_type, value)
    return f.read()            

def domain_list():
    url = 'https://www.dnspod.com/API/Record.List'
    data = {'login_email':'xiaojay@gmail.com',
            'login_password':'101783',
            'format':'json',
            'domain_id':jayproxy_domain_id,}
    f = urllib2.urlopen(url, urllib.urlencode(data))
    return f.read()

def check_connect(url):
    #print url
    socket.setdefaulttimeout(5)
    try:
        f = urllib.urlopen(url)  
    except IOError,e:
        '''
        errno, errstr = sys.exc_info()[:2]
        if str(errstr).find('timed out') !=-1:
            return False
        if str(errstr).find('reset') !=-1:
            return False
        '''
        #print app_id, e
        return False
    else:
        code = f.getcode()
        #print code
        if code == 200:
            return True
        else:
            return False

if __name__  == '__main__':
    fn = 'last_modified_at.pk'
    m5 = datetime.timedelta(minutes=5)
    
    if os.path.exists(fn):
        t = pickle.load(open(fn))
        print 'last modified at %s'%t
        now = datetime.datetime.now()
        if (now-t) < m5:
            sys.exit()
            
    if not check_connect(jayproxy_url):
        print 'jayproxy.com is down.'
        for n in ['hp', 'zjuer', 'fdd']:
            v = vps[n]
            url = 'http://' + v[1]
            if check_connect(url):
                print '%s is ok'%n 
                print modify(v[0], v[1])
                now = datetime.datetime.now()
                pickle.dump(now, open(fn, 'w'))
                sys.exit()
    print 'jayproxy.com is ok' 
